package org.example.utils;

import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author liyishan
 * @date 2023/4/18 16:21
 */

public class XmlUtils {
    static DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

    public XmlUtils() {
    }

    public static DocumentBuilder getDocumentBuilder() {
        try {
            return documentBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException var1) {
            System.err.println("XmlUtils获取失败");
            var1.printStackTrace();
            throw new RuntimeException("XmlUtils获取失败");
        }
    }

    public static Map<String, String> xmlToMap(String strXML) {
        try {
            Map<String, String> data = new HashMap();
            DocumentBuilder documentBuilder = getDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();

            for(int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == 1) {
                    Element element = (Element)node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }

            try {
                stream.close();
            } catch (Exception var9) {
            }

            return data;
        } catch (Exception var10) {
            throw new RuntimeException("XmlUtils parse error");
        }
    }

    public static String mapToXml(Map<String, String> data) {
        Document document = getDocumentBuilder().newDocument();
        Element root = document.createElement("xml");
        document.appendChild(root);
        Iterator var3 = data.keySet().iterator();

        String value;
        while(var3.hasNext()) {
            String key = (String)var3.next();
            value = (String)data.get(key);
            if (value == null) {
                value = "";
            }

            value = value.trim();
            Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        DOMSource source = new DOMSource(document);
        value = null;

        StringWriter writer;
        try {
            Transformer transformer = tf.newTransformer();
            transformer.setOutputProperty("encoding", "UTF-8");
            transformer.setOutputProperty("indent", "yes");
            writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);
        } catch (TransformerException var9) {
            throw new RuntimeException("parse error ");
        }

        String output = writer.getBuffer().toString();

        try {
            writer.close();
        } catch (Exception var8) {
        }

        return output;
    }

    public static String getElementValue(String xmlString, String... nodeNames) {
        org.dom4j.Element element = null;

        try {
            org.dom4j.Document documen = DocumentHelper.parseText(xmlString);
            element = documen.getRootElement();
            String[] var4 = nodeNames;
            int var5 = nodeNames.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                String nodeName = var4[var6];
                if (null == element) {
                    return null;
                }

                element = element.element(nodeName);
            }

            if (null == element) {
                return null;
            } else {
                return element.getText();
            }
        } catch (DocumentException var8) {
            var8.printStackTrace();
            return null;
        }
    }

    static {
        try {
            documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
            documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
            documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            documentBuilderFactory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);
        } catch (ParserConfigurationException var1) {
            System.err.println("XmlUtils初始化失败");
        }

        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);
    }
}
